// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "CaeThread.h"

CaeThread::CaeThread()
{
    m_tid = 0;
    m_threadStatus = CAE_THREAD_STATUS_NEW;
}

CaeThread::~CaeThread()
{
    m_threadStatus = CAE_THREAD_STATUS_EXIT;
    Join();
}


void *ThreadProxyFunc(void *args)
{
    auto *pThread = static_cast<CaeThread *>(args);
    pThread->Run();
    return nullptr;
}

bool CaeThread::Start()
{
    m_threadStatus = CAE_THREAD_STATUS_RUNNING;
    return pthread_create(&m_tid, nullptr, ThreadProxyFunc, this) == 0;
}

void CaeThread::Join() const noexcept
{
    if (m_tid > 0) {
        pthread_join(m_tid, nullptr);
    }
}

void CaeThread::Stop() noexcept
{
    if (m_threadStatus == CAE_THREAD_STATUS_EXIT) {
        return;
    }
    m_threadStatus = CAE_THREAD_STATUS_STOP;
}
